package com.cda.pes.controller;

import com.cda.pes.pojo.Product;
import com.cda.pes.service.IProductService;
import com.cda.pes.service.ex.ProductNotFoundException;
import com.cda.pes.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.channels.Pipe;
import java.util.List;

@RestController
@RequestMapping("products")
public class ProductController extends BaseController {
    @Autowired
    private IProductService productService;

    @RequestMapping("hot_list")
    public JsonResult<List<Product>> getHotList() {
        List<Product> data = productService.findHotList();
        return new JsonResult<List<Product>>(OK, data);
    }

    @RequestMapping("new_list")
    public JsonResult<List<Product>> getLastedList() {
        List<Product> data = productService.findLastedList();
        return new JsonResult<List<Product>>(OK, data);
    }

    @GetMapping("{id}/details")
    public JsonResult<Product> getById(@PathVariable("id") Integer id) {
        // 调用业务对象执行获取数据
        Product data = productService.findById(id);
        // 返回成功和数据
        return new JsonResult<Product>(OK, data);
    }

    @RequestMapping("addproduct")
    public JsonResult<Product> addProduct(Product product){
        Integer rows = productService.addProduct(product);
        return new JsonResult<>(OK);
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public JsonResult<Void> deleteProduct(@PathVariable("id") Integer id){
        productService.deleteProduct(id);
        return new JsonResult<>(OK);
    }

    @RequestMapping("findall")
    public JsonResult<List<Product>> findAll(){
        List<Product> data = productService.findAll();
        return new JsonResult<List<Product>>(OK,data);
    }

    @RequestMapping("{typename}/findbytype")
    public JsonResult<List<Product>> findAllByType(@PathVariable("typename") String typename){
        List<Product> data = productService.findAllByType(typename);
        if (data.size() < 1){
            throw new ProductNotFoundException("未找到该类型商品");
        }
        return new JsonResult<List<Product>>(OK,data);
    }

    @RequestMapping("update/{id}")
    public JsonResult<Void> updateProduct(Product product,@PathVariable("id") Integer id){
        System.out.println(product);
        productService.updateProduct(product);
        System.out.println(productService.findById(id));
        return new JsonResult<>(OK);
    }
}
